package com.pcj.blog.service;/**
 * @param
 * @author pcj
 * @date 2021/12/28 19:03
 * @return
 */

import com.pcj.blog.NotFoundException;
import com.pcj.blog.dao.TagRepository;
import com.pcj.blog.po.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @className TagServiceImpl
 * @author pengcj
 * @date 2021/12/28 19:03
 */
@Service
public class TagServiceImpl implements  TagService{
    @Autowired
    private TagRepository tagRepository;
    @Override
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }

    @Override
    public Tag updataTag(Long id, Tag tag) {
        Tag t=tagRepository.getById(id);
        if(t==null){
            throw new NotFoundException("不存在该标签");
        }
        BeanUtils.copyProperties(tag,t);
        return tagRepository.save(t);
    }

    @Override
    public Tag getTagByid(Long id) {
        return tagRepository.getById(id);
    }

    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    @Override
    public void deleteTag(Long id) {
        tagRepository.deleteById(id);
    }

    @Override
    public Tag getTagByName(String name) {
        return tagRepository.findByName(name);
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }

    @Override
    public List<Tag> listTag(String ids) {  //根据前端传过来的 {1，2，3} 查到标签
        return tagRepository.findAllById(idlist(ids));
    }

    @Override
    public List<Tag> listTop(Integer size) {
        Sort sort= Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable=PageRequest.of(0,size,sort);
        return tagRepository.findTop(pageable);
    }

    private List<Long> idlist( String ids){

        List<Long >list=new ArrayList<>();
        if(!"".equals(ids) && ids!=null){
            String [] idarr =ids.split(",");
            for(String  id:idarr){
                list.add(new Long(id));
            }
        }
        return list;
    }
}
